package com.example.hrmsaas.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.hrmsaas.system.controller.PermissionController;
import com.example.hrmsaas.system.entity.*;
import com.example.hrmsaas.system.mapper.PermissionMapper;
import com.example.hrmsaas.system.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.hrmsaas.system.utils.BeanMapUtils;
import com.example.hrmsaas.system.utils.DataGridView;
import com.example.hrmsaas.system.utils.IdWorker;
import com.example.hrmsaas.system.utils.PermissionConstants;
import com.example.hrmsaas.system.utils.vo.PermissionVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 雷哥
 * @since 2021-11-10
 */
@Service
@Transactional
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {

    private Log log = (Log) LogFactory.getLog(PermissionController.class);

    @Autowired
    IPermissionMenuService permissionMenuService;

    @Autowired
    IPermissionPointService permissionPointService;

    @Autowired
    IPermissionapiService permissionapiService;

    @Autowired
    PermissionMapper permissionMapper;

    @Override
    public DataGridView getPermissionList(PermissionVo permissionVo) {
        QueryWrapper<Permission> premQw = new QueryWrapper<Permission>();
            if(permissionVo.getType() !=null){
                premQw.eq("type",permissionVo.getType());
            }
        premQw.eq(StringUtils.isNotBlank(permissionVo.getPid()),"pid",permissionVo.getPid());
            if(permissionVo.getEnVisible()!=null){
                premQw.eq("en_visible",permissionVo.getEnVisible());
            }
        premQw.orderByDesc("id");
        Page<Permission> page = new Page<Permission>(permissionVo.getPage(),permissionVo.getLimit());
        permissionMapper.selectPage(page,premQw);
        List<Permission> list = page.getRecords();
        return  new DataGridView(page.getTotal(),list);
    }

    private ApplicationContext content;
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

    }

    @Override
    public boolean add(Map<String, Object> map) throws Exception {
        IdWorker idWorker = new IdWorker();
        String id = idWorker.nextId() + "";
        //1.通过map构造Permission对象
        Permission perm = BeanMapUtils.mapToBean(map, Permission.class);
        perm.setId(id);
        //2.根据属性的不同构建不同的资源对象（按钮，菜单，接口）
        int type = perm.getType();
        boolean saveStatus;
        Exception e = new Exception();
        switch (type) {
            case PermissionConstants.PY_MENU:
                PermissionMenu menu = BeanMapUtils.mapToBean(map, PermissionMenu.class);
                menu.setId(id);
                saveStatus = permissionMenuService.add(menu);
                if(!saveStatus) {
                    log.info("PermissionMenu执行保存出现异常："+ e.getMessage());
                }
                break;
            case PermissionConstants.PY_API:
                PermissionApi api = BeanMapUtils.mapToBean(map, PermissionApi.class);
                api.setId(id);
                saveStatus = permissionapiService.add(api);

                if(!saveStatus) {
                    log.info("PermissionApi执行保存出现异常："+ e.getMessage());
                }
                break;

            case PermissionConstants.PY_POINT:
                PermissionPoint point = BeanMapUtils.mapToBean(map,PermissionPoint.class);
                point.setId(id);
                saveStatus = permissionPointService.add(point);
                if(!saveStatus) {
                    log.info("PermissionPoint执行保存出现异常："+ e.getMessage());
                }
                break;

            default:

                return false;
        }
        //执行保存操作
        if(saveStatus){
           int code =  permissionMapper.insert(perm);
           if(code>0){
               return true;
           }else{
               log.info("Permission执行保存出现异常："+ e.getMessage());
               return false;
           }
        }else{
            return false;
        }

    }

    @Override
    public boolean edit(Map<String, Object> map) throws Exception {
        Permission perm = BeanMapUtils.mapToBean(map, Permission.class);
        Permission oldperm = permissionMapper.selectById(perm.getId());
        oldperm.setCode(perm.getCode()!=""?perm.getCode():oldperm.getCode());
        oldperm.setName(perm.getName()!=""?perm.getName():oldperm.getName());
        oldperm.setDescription(perm.getDescription()!=""?perm.getDescription():oldperm.getDescription());
        oldperm.setEnVisible(perm.getEnVisible()!=""?perm.getEnVisible():oldperm.getEnVisible());
        //2.根据属性的不同构建不同的资源对象（按钮，菜单，接口）
        int type = oldperm.getType();
        boolean saveStatus;
        Exception e = new Exception();
        switch (type) {
            case PermissionConstants.PY_MENU:
                PermissionMenu menu = BeanMapUtils.mapToBean(map, PermissionMenu.class);
                menu.setId(oldperm.getId());
                saveStatus = permissionMenuService.updateById(menu);
                if(!saveStatus) {
                    log.info("PermissionMenu执行更新出现异常："+ e.getMessage());
                }
                break;
            case PermissionConstants.PY_API:
                PermissionApi api = BeanMapUtils.mapToBean(map, PermissionApi.class);
                api.setId(oldperm.getId());
                saveStatus = permissionapiService.updateById(api);

                if(!saveStatus) {
                    log.info("PermissionApi执行更新出现异常："+ e.getMessage());
                }
                break;

            case PermissionConstants.PY_POINT:
                PermissionPoint point = BeanMapUtils.mapToBean(map,PermissionPoint.class);
                point.setId(oldperm.getId());
                saveStatus = permissionPointService.updateById(point);
                if(!saveStatus) {
                    log.info("PermissionPoint执行更新出现异常："+ e.getMessage());
                }
                break;

            default:

                return false;
        }
        //执行保存操作
        if(saveStatus){
            int code =  permissionMapper.updateById(perm);
            if(code>0){
                return true;
            }else{
                log.info("Permission执行保存出现异常："+ e.getMessage());
                return false;
            }
        }else{
            return false;
        }
    }


    @Override
    public boolean del(String id) throws Exception {
        Permission oldperm = permissionMapper.selectById(id);
        //2.根据属性的不同构建不同的资源对象（按钮，菜单，接口）
        int type = oldperm.getType();
        boolean delStatus;
        Exception e = new Exception();
        switch (type) {
            case PermissionConstants.PY_MENU:
                delStatus = permissionMenuService.delet(oldperm.getId());
                if(!delStatus) {
                    log.info("permissionMenuService执行删除出现异常："+ e.getMessage());
                }
                break;
            case PermissionConstants.PY_API:
                delStatus = permissionapiService.delet(oldperm.getId());
                if(!delStatus) {
                    log.info("permissionapiService执行删除出现异常："+ e.getMessage());
                }
                break;

            case PermissionConstants.PY_POINT:
                delStatus = permissionPointService.delet(oldperm.getId());
                if(!delStatus) {
                    log.info("permissionPointService执行删除出现异常："+ e.getMessage());
                }
                break;

            default:

                return false;
        }
        //执行保存操作
        if(delStatus){
            int code =  permissionMapper.deleteById(id);
            if(code>0){
                return true;
            }else{
                log.info("permissionService执行删除出现异常："+ e.getMessage());
                return false;
            }
        }else{
            return false;
        }
    }

    @Override
    public DataGridView info(String id) throws Exception {
        Permission pr = permissionMapper.selectById(id);
        Object objct = null;
        switch (pr.getType()) {
            case PermissionConstants.PY_MENU:
                objct = permissionMenuService.getInfoByid(id);
                break;
            case PermissionConstants.PY_API:
                objct = permissionapiService.getInfoByid(id);
                break;

            case PermissionConstants.PY_POINT:
                objct = permissionPointService.getInfoByid(id);
                break;
        }
        Map<String,Object> map = BeanMapUtils.beanToMap(objct);
        map.put("name",pr.getName());
        map.put("code",pr.getCode());
        map.put("description",pr.getDescription());
        map.put("pid",pr.getPid());
        map.put("en_visible",pr.getEnVisible());
        map.put("type",pr.getType());
        return  new DataGridView((long) 0,map);
    }

    @Override
    public Permission getById(String id) {
        return permissionMapper.selectById(id);
    }

    @Override
    public List<Permission> getPermissionAll(PermissionVo permVo) {
        QueryWrapper<Permission> premQw = new QueryWrapper<Permission>();
        if(permVo.getType() > 0){
            premQw.eq("type",permVo.getType());
        }

        if(!StringUtils.isEmpty(permVo.getEnVisible())){
            premQw.eq("en_visible",permVo.getEnVisible());
        }

        premQw.orderByDesc("id");
        List<Permission> list = permissionMapper.selectList(premQw);
        return  list;
    }

    @Override
    public List<Permission> findByTypeAndPid(int pyApi, String id) {
        PermissionVo permVo = new PermissionVo();
        permVo.setType(pyApi);
        permVo.setPid(id);
        QueryWrapper<Permission> premQw = new QueryWrapper<Permission>();
        premQw.eq("type",permVo.getType());
        premQw.eq("pid",permVo.getPid());
        premQw.orderByDesc("id");
        return permissionMapper.selectList(premQw);
    }
}
